<!--
 * @Author: your name
 * @Date: 2020-05-29 15:37:29
 * @LastEditTime: 2020-07-02 19:02:56
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \IM_Web\im_web\src\views\login\index.vue
--> 
<template>
    <div class="login flex align_center justify_center">
        <div class="login_page_content flex justify_between">
            <div class="content_logo"></div>
            <div>
                <div class="title">企内聊</div>
                <Form ref="formInline" :model="formInline" :rules="ruleInline">
                    <FormItem prop="acount">
                        <div class="form_item flex align_center">
                            <div class="form_icon acount_icon"></div>
                            <iInput
                                type="text"
                                :maxlength="11"
                                v-model="formInline.acount"
                                placeholder="请输入账号"
                            ></iInput>
                        </div>
                    </FormItem>
                    <FormItem prop="password" style="margin-bottom:15px;" v-if="loginType">
                        <div class="form_item flex align_center">
                            <div class="form_icon pwd_icon"></div>
                            <iInput
                                type="password"
                                v-model="formInline.password"
                                placeholder="请输入登录密码"
                            ></iInput>
                        </div>
                    </FormItem>
                    <div v-else>
                        <FormItem prop="answer" style="margin-bottom:15px;" v-show="isAnswerBox">
                            <div class="form_item flex align_center">
                                <div class="form_icon pwd_icon"></div>
                                <iInput
                                    type="text"
                                    v-model="formInline.answer"
                                    placeholder="请输入答案"
                                    style="width:140px;"
                                    v-show="isAnswerBox"
                                ></iInput>
                                <div @click="refreshCode()">
                                    <s-identify :identifyCode="identifyCode" :contentWidth="100"></s-identify>
                                </div>
                            </div>
                        </FormItem>
                        <FormItem
                            prop="identifyCode"
                            style="margin-bottom:15px;"
                            v-show="!isAnswerBox"
                        >
                            <div class="form_item flex align_center justify_between">
                                <div class="flex align_center">
                                    <div class="form_icon pwd_icon"></div>
                                    <iInput
                                        type="text"
                                        v-model="formInline.identifyCode"
                                        placeholder="请输入验证码"
                                        style="width:140px;"
                                    ></iInput>
                                </div>
                                <Button
                                    :disabled="countdownNumber!==60"
                                    @click="getIdentifyCode()"
                                >{{countdownNumber===60?'重新发送':`${countdownNumber}秒后`}}</Button>
                            </div>
                        </FormItem>
                    </div>
                    <!-- <FormItem prop="captcha">
                        <iInput type="text" v-model="formInline.captcha" placeholder="Code"></iInput>
                    </FormItem>-->
                    <FormItem style="margin-bottom:17px;">
                        <div class="n flex justify_between align_center color_333">
                            <div @click="changeLogin">{{loginType?'短信登录':'密码登录'}}</div>
                            <div @click="$router.push('/passport')">忘记密码</div>
                        </div>
                    </FormItem>
                    <FormItem>
                        <Button
                            type="primary"
                            @click="handleSubmit('formInline')"
                            class="sub_btn"
                            :loading="loading"
                        >登录</Button>
                    </FormItem>
                </Form>
                <div class="dowload_code_box flex justify_between">
                    <div class="flex flex_direction align_center">
                        <div class="dowload_code flex align_center justify_center">
                            <div class="android_dowload_code"></div>
                        </div>
                        <div>安卓APP下载</div>
                    </div>
                    <div class="flex flex_direction align_center">
                        <div class="ios_dowload_code dowload_code flex align_center justify_center">
                            <div class="android_dowload_code"></div>
                        </div>
                        <div>苹果APP下载</div>
                    </div>
                </div>
                <!-- <Input v-model="acount" placeholder="Enter something..." style="width: 300px" /> -->
                <!-- <Input v-model="pwd" placeholder="Enter something..." style="width: 300px" /> -->
            </div>
        </div>
    </div>
</template>

<script>
import SIdentify from "../../components/sidentify/index.vue";
let timer = null;
export default {
    inject: ["reload"],
    props: {},
    data() {
        const validateMobile = (rule, value, callback) => {
            // 自定义表单验证,验证手机号是否正确
            // console.log(rule, value);
            if (!this.http.myregMobile.test(value) || value.length < 11) {
                callback(new Error("请输入正确的手机号"));
            } else {
                callback();
            }
        };
        const validateAnswer = (rule, value, callback) => {
            // 验证答案是否正确
            if (this.formInline.acount === "") {
                callback(new Error("请输入手机号"));
                return;
            }
            // console.log(5555);
            if (Number(value) === this.answer) {
                // console.log(1);
                if (this.ruleInline.answer[0].required) {
                    // 第一次验证通过时获取短信验证码
                    this.getIdentifyCode();
                }
                this.ruleInline.answer[0].required = false;
                this.ruleInline.identifyCode[0].required = true;
                this.isAnswerBox = false;
                callback();
            } else {
                // 答案不正确显示提示语并重新生成
                this.formInline.answer = "";
                this.refreshCode();
                callback(new Error("答案不正确"));
            }
        };
        return {
            formInline: {
                acount: "", //手机号
                password: "", //密码
                identifyCode: "", //短信验证码
                answer: "" //答案
            }, //表单字段
            ruleInline: {
                acount: [
                    {
                        required: true,
                        message: "请输入账号",
                        trigger: "blur"
                    },
                    {
                        validator: validateMobile,
                        trigger: "blur"
                    }
                ],
                password: [
                    {
                        required: true,
                        message: "请输入登入密码",
                        trigger: "blur"
                    }
                ],
                identifyCode: [
                    {
                        required: false,
                        message: "请输入验证码",
                        trigger: "blur"
                    }
                ],
                answer: [
                    {
                        required: true,
                        message: "请输入答案",
                        trigger: "blur"
                    },
                    {
                        validator: validateAnswer,
                        trigger: "blur"
                    }
                ]
            }, //表单验证规则
            countdownNumber: 60, //获取短信倒计时
            loading: false, //按钮显示loading
            identifyCodes: "1234567890", //
            symbol: ["+", "-", "*"],
            identifyCode: "", //传递给验证码组件显示的字符串
            answer: "", //计算所得的答案
            isAnswerBox: true, //是否显示短信验证码输入框
            loginType: true //切换短信登录-密码登录
        };
    },
    computed: {},
    created() {
        this.ruleInline.password[0].required = this.loginType;
        this.ruleInline.answer[0].required = !this.loginType;
    },
    mounted() {
        this.identifyCode = "";
        this.makeCode(this.identifyCodes, 4);
    },
    watch: {},
    methods: {
        countdown() {
            // 短信验证码获取倒计时
            timer = setInterval(() => {
                if (this.countdownNumber === 0) {
                    this.clearCountdown();
                    return;
                }
                --this.countdownNumber;
            }, 1000);
        },
        handleSubmit(name) {
            // 提交表单
            // this.$router.push('/')
            this.$refs[name].validate(valid => {
                if (valid) {
                    this.loading = true;
                    // 提交成功执行登录
                    this.webMemberLogin();
                    // this.$Message.success("Success!");
                } else {
                    // this.$Message.error("Fail!");
                }
            });
        },
        clearCountdown() {
            // 清除定时器并重置倒计时数字
            clearInterval(timer);
            this.countdownNumber = 60;
        },
        changeLogin() {
            this.ruleInline.password[0].required = !this.ruleInline.password[0]
                .required;
            this.ruleInline.answer[0].required = !this.ruleInline.answer[0]
                .required;
            if (this.countdownNumber === 60) {
                this.refreshCode();
            }
            this.loginType = !this.loginType;
            this.formInline.password = "";
            this.formInline.answer = "";
            // this.isAnswerBox = true;
            // this.clearCountdown();
            // this.ruleInline.identifyCode[0].message = this.ruleInline
            //     .identifyCode[0].required
            //     ? "请输入答案"
            //     : "";
            // this.ruleInline.password[0].message = this.ruleInline.password[0]
            //     .required
            //     ? "请输入登入密码"
            //     : "";
        },
        getIdentifyCode() {
            // 获取短信验证码
            let params = {
                mobile: this.formInline.acount,
                type: "login"
            };
            this.http.getVerify(params).then(res => {
                console.log(res);
                this.$Message.destroy();
                res.data.errno === "000"
                    ? this.$Message.success(res.data.errmsg)
                    : this.$Message.error(res.data.errmsg);
                this.countdown();
            });
        },
        webMemberLogin() {
            let pwd = this.loginType ? this.formInline.password : "";
            let code = !this.loginType ? this.formInline.identifyCode : "";
            // let params = `mobile=${this.formInline.acount}&device_type=web&password=${pwd}&code=${code}`;
            let params = {
                mobile: this.formInline.acount,
                device_type: 3, //客户端类型
                password: pwd,
                code: code
            };
            // this.$getCode(params).then(rsaCode=>{
            // console.log(rsaCode)
            this.http.webLogin(params).then(res => {
                console.log(res.data);
                // this.loading = false;
                this.$Message.destroy();
                this.loading = false;
                if (res.data.errno !== "000") {
                    this.$Message.error(res.data.errmsg);
                } else {
                    sessionStorage.setItem("t", res.data.result.data.auth);
                    sessionStorage.setItem(
                        "info",
                        JSON.stringify(res.data.result.data)
                    );
                   
                    this.$router.push("/");
                    // this.init(res.data.result.data.token,res.data.result.data.accid);
                    // this.$store.dispatch('initNimSDK')
                }
            });
            // })
            // console.log(params);
        },
        //验证码
        randomNum(min, max, index) {
            let n = "";
            switch (index) {
                case 0:
                    // 生成第一个数
                    n = Math.floor(Math.random() * (max - min) + min);
                    n === 0 ? Math.floor(Math.random() * (max - min) + min) : n;
                    break;
                case 1:
                    // 生成运算符号
                    n = this.symbol[Math.floor(Math.random() * 3)];
                    break;
                case 2:
                    // 生成第二个数
                    n = Math.floor(Math.random() * (max - min) + min);
                    break;
                case 3:
                    n = "=?";
                    break;
            }
            return n;
        },
        refreshCode() {
            // 刷新验证码
            // this.clearCountdown();
            this.identifyCode = "";
            this.makeCode(this.identifyCodes, 4);
        },
        makeCode(o, l) {
            let rand = "";
            this.answer = "";
            let answer = [];
            for (let i = 0; i < l; i++) {
                rand = this.randomNum(1, this.identifyCodes.length, i);
                // console.log(rand);
                answer.push(rand);
                this.identifyCode += rand;
                // this.identifyCodes[
                //     this.randomNum(0, this.identifyCodes.length,i)
                // ];
            }
            // console.log(answer);
            this.answer =
                answer[1] === "+"
                    ? answer[0] + answer[2]
                    : answer[1] === "-"
                    ? answer[0] - answer[2]
                    : answer[0] * answer[2];
            // console.log(this.identifyCode);
        }
    },
    components: {
        SIdentify
    }
};
</script>
<style>
.form_item .ivu-input {
    border: 0;
}
.form_item .ivu-input:focus {
    box-shadow: 0px 0px 0px rgb(255, 255, 255) !important;
}
.form_item .ivu-input {
    background: #fff !important;
}
</style>
<style scoped lang="less">
@import url("./index.less");
</style>
